#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import tarfile
import sys

#print("IN EPISTASIS PY")

def main():
    """Load pkl-file"""
    print("32) EPIST pkl-file is loaded") 	
    job = load_job_data()
    print("33) EPIST job is passed to run_epistasis script") 	
    run_epistasis_job(job)


def run_epistasis_job(job):
    create_dir(job['output_dir'], True)
    # create and enter output dir
    """job['output_dir'] is the filename epifiles/"""
    print("34) EPIST The folder epifiles is added to the tmp-folder")
    """Is this tmp-epifles used at all? intermediate to gx-file??"""

    """Here the real programme is started in Py"""
    execute_epistasisP(job,"../") # execute program

    archive_name = job["output_files"][0]      
    """this is the epifileX.tar.gz file"""

    os.chdir("../")
    archive_output(target_dir=job["output_dir"], dest_dir="./",arc_name=archive_name) # archive output dir
    clean_up_epistasis(job["output_dir"], [archive_name, job["main_script"]]) 

def extract_job_files(filepath, dest_dir):
    prog_files = tarfile.open(dest_dir+filepath, "r")
    prog_files.extractall(path=dest_dir)
    prog_files.close()

def create_dir(dir_path, enter_directory=False):

    if os.path.exists(dir_path):
        if enter_directory :
            os.chdir(dir_path)
    else: 
        os.mkdir(dir_path)
        if enter_directory:
            os.chdir(dir_path)

def archive_output(target_dir, arc_name, dest_dir):
    output_files = tarfile.open(dest_dir+arc_name, 'w:gz')
    output_files.add(target_dir, arcname="")
    output_files.close()

def clean_up_epistasis(working_dir_path, exceptions_list):    
    for root, dirs, files in  os.walk(working_dir_path, topdown=False):
        for f in files: 
            if f[-6:] != ".tar.gz" and not f in exceptions_list :
                fil = os.path.join(root,f)
                os.remove(fil)
#                print "removed "+fil
        if dirs != [] :
            direct = os.path.join(root,dirs[0])
            os.rmdir(direct)
#            print "removed "+direct
        
    os.rmdir(working_dir_path)
                    
def execute_epistasisP(job,path):
    print("35) EPIST Execute_epistasisP")
    import epicalcP
    epicalcP.epi_selection(job)    

        
def load_job_data():
    import pickle
    job_file = sys.argv[1]
    #pkl_file = open("job_file.pkl", 'rb')
    
    pkl_file = open(job_file, 'rb')
    #pkl_file = open('job_file.pkl', 'rb')
    data1 = pickle.load(pkl_file)
#    print(data1)
    pkl_file.close()
#    print "loaded job data: ", data1
    return data1
     #pickle.load(job, pickledfile)
       
if __name__ == "__main__":
    main()
